const BasicAuth = require('basic-auth')
const jwt = require('jsonwebtoken')

class Auth {

  get m() {
    return async (ctx, next) => {
      // 前端headers
      // ==================
      // headers: {
      //   Authorization: Base64.encode('Basic '+ token)
      // }
      // ==================
      // ====in axios======
      // auth: {
      //   username: token,
      //   password: ''
      // }
      // ==================
      // ====end====
      // 正常流程
      const userToken = BasicAuth(ctx.req)
      let decode = {}
      if (!userToken || !userToken.name) {
        throw new global.errs.Forbbiden('尚未登录')
      }
      try {
        decode = jwt.verify(userToken.name, global.config.security.secretKey)
      } catch (err) {
        if (err.name === 'TokenExpiredError') {
          throw new global.errs.Forbbiden('token已过期')
        } else if (err.name === 'JsonWebTokenError') {
          throw new global.errs.Forbbiden('token无效')
        } else {
          throw new global.errs.Forbbiden('权限认证失效')
        }
      }
      ctx.auth = {
        uid: decode.uid
      }
      await next()
    }
  }

  static verifyToken(token) {
    try {
      jwt.verify(token, global.config.security.secretKey)
      return true
    } catch(e) {
      return false
    }
  }

  static generateToken(uid) {
    const secretKey = global.config.security.secretKey
    const expiresIn = global.config.security.expiresIn
    const token = jwt.sign({ uid }, secretKey, { expiresIn })
    return token
  }
}

module.exports = {
  Auth
}